package com.crowntit.trigger.http;

import com.crowntit.api.IIndexService;
import com.crowntit.api.dto.QueryProductConfigReqDTO;
import com.crowntit.api.dto.QueryProductConfigResDTO;
import com.crowntit.api.response.Response;
import com.crowntit.domain.goods.model.entity.GoodsConfigInfoEntity;
import com.crowntit.domain.goods.model.entity.QueryGoodsConfigEntity;
import com.crowntit.domain.goods.service.IGoodsService;
import com.crowntit.domain.order.service.IOrderService;
import com.crowntit.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@RestController()
@CrossOrigin("*")
@RequestMapping("/api/v1/index/")
public class IndexController implements IIndexService {

    @Resource
    private IGoodsService goodsService;

    @Override
    @RequestMapping(value = "query_product_config", method = RequestMethod.POST)
    public Response<QueryProductConfigResDTO> queryProductConfig(@RequestBody QueryProductConfigReqDTO requestDTO) {
        String userId = requestDTO.getUserId();
        String productId = requestDTO.getProductId();

        if (StringUtils.isBlank(productId)){
            return Response.<QueryProductConfigResDTO>builder()
                    .code(Constants.ResponseCode.PARAMETER_ERROR.getCode())
                    .message(Constants.ResponseCode.PARAMETER_ERROR.getInfo())
                    .data(null)
                    .build();
        }

        QueryProductConfigResDTO queryProductConfigResDTO = null;
        try {
            GoodsConfigInfoEntity goodsConfigInfoEntity = goodsService.queryGoodsConfigInfo(QueryGoodsConfigEntity.builder()
                    .productId(productId)
                    .userId(userId)
                    .build());
            Integer isGroupBuyConfig = goodsConfigInfoEntity.isGroupBuyConfig() ? 1 : 0;

            queryProductConfigResDTO = QueryProductConfigResDTO.builder()
                    .groupBuyTeamList(goodsConfigInfoEntity.getGroupBuyTeamList())
                    .goods(goodsConfigInfoEntity.getGoods())
                    .isGroupBuyConfig(isGroupBuyConfig)
                    .build();
        } catch (IOException e) {
            log.error("查询商品信息错误: {}", e.getMessage());
            return Response.<QueryProductConfigResDTO>builder()
                    .code(Constants.ResponseCode.ERROR.getCode())
                    .message(Constants.ResponseCode.ERROR.getInfo())
                    .data(null)
                    .build();
        }

        return Response.<QueryProductConfigResDTO>builder()
                .code(Constants.ResponseCode.SUCCESS.getCode())
                .message(Constants.ResponseCode.SUCCESS.getInfo())
                .data(queryProductConfigResDTO)
                .build();
    }
}
